package cn.itcast;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;

public class ElasticDemo {
    private TransportClient client = null;

    //初始化客户端,并且连接elasticSearch,使用的是tcp协议,端口号为9300
    @Before
    public void init() throws Exception {
        client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
    }
    @Test
    public void queryTest() {
        //查询方式
        //查询所有
       // QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        //分词查询
      // QueryBuilder queryBuilder = QueryBuilders.termQuery("goodsName", "手机");
        //容错查询,设置容错读只有FuzzyQueryBuilder对象才有此方法
       /* FuzzyQueryBuilder queryBuilder = QueryBuilders.fuzzyQuery("goodsName", "手及");
        queryBuilder.fuzziness(Fuzziness.ONE);*/
        //范围查询
       // QueryBuilder queryBuilder = QueryBuilders.rangeQuery("price").gte(1000).lte(2000);
//组合查询
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.rangeQuery("price").gte(1000).lte(8000));
        queryBuilder.mustNot(QueryBuilders.termQuery("goodsName", "华为"));
//get()是用来发送请求的,参数要传一个queryBuilder
        SearchResponse searchResponse = client.prepareSearch("heima").setQuery(queryBuilder).get();
        SearchHits searchHits = searchResponse.getHits();
        long totalHits = searchHits.getTotalHits();
        System.out.println("一共有"+totalHits);
        //获取索引库中的所有对象
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //使用fastJson来转成实体Bean
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            System.out.println(goods);
        }
    }
    @After
    public void end() {
        client.close();
    }
}
